package catalogue

import (
	"clouds.lgb24kcs.cn/controllers/catalogue/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/history"
	"clouds.lgb24kcs.cn/utils/oss"
	"errors"
	"github.com/gin-gonic/gin"
	"time"
)

type DetailCataloguetAPI struct {
}

var DetailAPI DetailCataloguetAPI

func (a *DetailCataloguetAPI) CatalogueDetail(c *gin.Context, req request.CatalogueDetailsReq, UserId int64) {
	catalogueInfo := models.Catalogue{}
	api := oss.OSS{}

	tx := global.APP.DB.Where("id=? and bucketid=? and userid=?", req.CatalogueId, req.BucketID, UserId).First(&catalogueInfo)
	if tx.Error != nil || tx.RowsAffected == 0 {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.CatalogueDetailsl, errors.New("目录详情信息获取失败").Error())
	} else {
		//查询Bucket信息，主要获取oss的秘钥信息
		BucketInfo := models.Storage{}
		first := global.APP.DB.Where("id=? and userid=?", catalogueInfo.Bucketid, UserId).First(&BucketInfo)
		if first.Error != nil || first.RowsAffected == 0 {
			global.APP.Log.Error(first.Error.Error())
			utils.Fail(c, errorx.CatalogueDetailsl, errors.New("目录详情信息获取失败").Error())
		} else {
			// 校验目录对象是否存在
			client := api.NewClient(BucketInfo.Accesskey, BucketInfo.Secretkey, BucketInfo.Zone)
			//svc := oss.NewAws(BucketInfo.Accesskey, BucketInfo.Secretkey, BucketInfo.Zone)
			if ok := api.CatalogueExists(client, req.BucketName, req.CatalogueName+"/"); !ok {
				utils.Fail(c, errorx.CatalogueDetailsl, errors.New("目录不存在").Error())
			} else {
				if err := history.HistoryCreate(UserId, c.Request.Method, c.Request.URL.String(), c.Request.Host); err != nil {
					utils.Fail(c, errorx.ObjectSearch, err.Error())
				} else {
					utils.Success(c, 0, request.CatalogueDetailsResp{List: request.CatalogueInfo{
						ID:            int64(catalogueInfo.ID),
						CatalogueName: catalogueInfo.Diskname,
						BucketName:    catalogueInfo.Bucketname,
						BucketId:      catalogueInfo.Bucketid,
						UserId:        catalogueInfo.Userid,
						CreateAt:      catalogueInfo.CreatedAt.Format(time.DateTime),
					}})
				}
			}
		}

	}
}
